package com.ruoyi.crypto.wrapper;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class ContentCachingHttpServletResponseWrapper extends HttpServletResponseWrapper {
    private final ByteArrayOutputStream content = new ByteArrayOutputStream();

    public ContentCachingHttpServletResponseWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                content.write(b);
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
            }
        };
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(content, true);
    }

    public byte[] getContentAsByteArray() {
        return content.toByteArray();
    }

    public void copyBodyToResponse() throws IOException {
        byte[] contentAsBytes = getContentAsByteArray();
        if (contentAsBytes.length > 0) {
            getResponse().getOutputStream().write(contentAsBytes);
        }
    }
}